package com.linfnn.demo.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

@RestController
public class EmailController_admin {

    @Value("${spring.mail.username}")
    String name;

    static String mailCode;
    @Autowired
    private JavaMailSender emailSender;



    @PostMapping("/sendLoginCode")
    public String sendLoginCodeEmail(@RequestParam("email") String recipientEmail) {
        String randomCode = generateRandomCode();
        sendEmail(recipientEmail, randomCode);
        return "<h1>验证码已经发送到你的邮箱，请你查看后，返回页面输入邮箱码</h1>";
    }



    @PostMapping("/checkCode")
    public ModelAndView checkCode(@RequestParam("mailCode") String code) {
        if (mailCode.equals(code)) {
            mailCode="null";
            return new ModelAndView("redirect:/managehtml/manage.html");
        }
        return new ModelAndView("redirect:/mailLogin_admin.html");

    }


    private String generateRandomCode() {
        Random random = new Random();
        int code = 1000 + random.nextInt(9000);
        mailCode=String.valueOf(code);
        return String.valueOf(code);
    }



    private void sendEmail(String recipientEmail, String randomCode) {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            message.setFrom(name);
            helper.setTo(recipientEmail);
            helper.setSubject("登录验证码");
            String htmlContent = "<html><body><p>尊敬的用户，您的登录验证码为：<strong>" + randomCode + "</strong></p><p>请在登录页面输入此验证码完成登录，验证码仅可使用一次。</p></body></html>";
            helper.setText(htmlContent, true);
            emailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
